import { getWindowInfo } from "@/utils/layout"
import { useEffect, useState } from "react"

/** 导航栏布局基本信息 */
export interface NavigationBaseLayout {
  /** 状态栏高度 */
  statusBarHeight: number
  /** 导航栏的高度
   * @value menuButtonHeight + Math.min(menuButtonPadding, menuButtonPadding + navigationOffset) * 2
   * @see `hooks#useLayout`
   */
  navigationHeight: number
}
/** 自定义导航栏布局信息 */
export interface NavigationLayout extends NavigationBaseLayout {
  /** 胶囊按钮高度 */
  menuButtonHeight: number
  /** 胶囊按钮距离状态栏的距离 */
  menuButtonPadding: number
  /** 计算导航栏高度的上下偏移量, 取值越大导航栏高度越高，最小值为`-menuButtonPadding`, 默认为0 */
  navigationOffset: number
}
export type NavigationLayoutIsReady = boolean
/** 导航栏布局基本信息
 * @default
 */
export const NAVIGATION_BASE_LAYOUT: NavigationBaseLayout = {
  statusBarHeight: 20,
  navigationHeight: 60
}
/** 自定义导航栏布局信息
 *  @default
 */
export const NAVIGATION_LAYOUT: NavigationLayout = {
  ...NAVIGATION_BASE_LAYOUT,
  menuButtonHeight: 50,
  menuButtonPadding: 5,
  navigationOffset: 0
}
/**
 * 获取设备状态栏和导航栏的布局信息, 用于自定义导航栏
 * @param [navigationOffset=0] 计算导航栏高度的上下偏移量, 取值越大导航栏高度越高，最小值为`-menuButtonPadding`, 默认为0
 */
export function useLayout(navigationOffset = 0): [NavigationLayout, NavigationLayoutIsReady] {
  const [layout, setLayout] = useState<NavigationLayout>(NAVIGATION_LAYOUT)
  const [isReady, setIsReady] = useState<NavigationLayoutIsReady>(false)
  useEffect(() => {
    const { statusBarHeight, menuButtonRect } = getWindowInfo()
    const menuButtonPadding = menuButtonRect.top - statusBarHeight
    setLayout({
      statusBarHeight,
      menuButtonHeight: menuButtonRect.height,
      menuButtonPadding,
      navigationHeight:
        menuButtonRect.height +
        Math.min(menuButtonPadding, menuButtonPadding + navigationOffset) * 2,
      navigationOffset
    })
    setIsReady(true)
  }, [])
  return [layout, isReady]
}
